package com.rrd.dw.mr.gzip;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.hbase.mapreduce.TableMapReduceUtil;
import org.apache.hadoop.hbase.mapreduce.TableMapper;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import com.rrd.dw.utils.HBaseUtil;

/**
 * Created by liuchuanqi on 2017/7/11.
 */
public class ExportUserBehaviorToDW extends Configured implements Tool {

    public static final String[] INFO_COLUMNS = { "app_bundle", "app_version",
        "lib_version", "jailbroken:boolean", "screen", "simulator:boolean",
        "network_type", "os", "wifi:boolean", "imei", "device_name", "language",
        "os_version", "model", "carrier" };
    public static final String[] EVENT_COLUMNS = { "uuid", "timestamp:long",
        "content", "event_name", "event_type", "action_type" };

    @Override
    public int run(String[] args) throws Exception {
        Properties prop = new Properties();
        try (InputStream is = this.getClass().getClassLoader()
            .getResourceAsStream("hbase.properties");) {
            prop.load(is);
        }

        Job job = Job.getInstance(HBaseConfiguration.create(this.getConf()));
        Configuration conf = job.getConfiguration();
        conf.set("hbase.zookeeper.quorum",
            prop.get("hbase.zookeeper.quorum").toString());
        conf.set("hbase.rootdir", prop.get("hbase.rootdir").toString());

        conf.set("mapreduce.map.memory.mb", "3072");
        conf.set("mapreduce.reduce.memory.mb", "5120");
        conf.set("hbase.client.scanner.timeout.period", "120");
        conf.set("mapreduce.output.fileoutputformat.compress", "true");
        conf.set("mapreduce.output.fileoutputformat.compress.type", "BLOCK");
        conf.set("mapreduce.output.fileoutputformat.compress.codec",
            "org.apache.hadoop.io.compress.GzipCodec");
        conf.set("io.compression.codecs",
            "org.apache.hadoop.io.compress.GzipCodec");
        conf.set("mapreduce.task.io.sort.factor", "10");
        String[] otherArgs = new GenericOptionsParser(conf, args)
            .getRemainingArgs();
        if (otherArgs.length != 3) {
            System.err
                .println("Usage: DataExportTool <out> <start_time> <end_time>");
            return -1;
        }
        Long startTime = HBaseUtil.parseDate(otherArgs[1]).getTime();
        Long endTime = HBaseUtil.parseDate(otherArgs[2]).getTime();
        job.setJarByClass(ExportUserBehaviorToDW.class);
        List<Scan> scans = new ArrayList<>();

        Scan scan = new Scan();
        scan.setCacheBlocks(false);
        scan.setCaching(200);
        scan.setAttribute(Scan.SCAN_ATTRIBUTES_TABLE_NAME,
            Bytes.toBytes("user_behavior_records"));
        scan.setTimeRange(startTime, endTime + 14400000);
        scans.add(scan);

        TableMapReduceUtil.initTableMapperJob(scans,
            ExportUserBehaviorToDWMapper.class, Text.class, Text.class, job);
        FileOutputFormat.setOutputPath(job, new Path(otherArgs[0]));
        MultipleOutputs.addNamedOutput(job, "baseinfo", TextOutputFormat.class,
            Text.class, Text.class);
        MultipleOutputs.addNamedOutput(job, "eventinfo", TextOutputFormat.class,
            Text.class, Text.class);

        job.setReducerClass(ExportUserBehaviorToDWReducer.class);
        job.setNumReduceTasks(5);
        return job.waitForCompletion(true) ? 0 : 1;

    }

    public static void main(String[] args) throws Exception {
        Configuration conf = HBaseConfiguration.create();
        int res = ToolRunner.run(conf, new ExportUserBehaviorToDW(), args);
        System.exit(res);
    }

    public static class ExportUserBehaviorToDWMapper
            extends TableMapper<Text, Text> {
        private SimpleDateFormat formatter = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");

        @Override
        protected void map(ImmutableBytesWritable key, Result value,
                Context context) throws IOException, InterruptedException {

            StringBuffer sb = new StringBuffer("");
            Object[] rowkey = HBaseUtil.decodeUserRowkey(value.getRow());
            if (rowkey == null) {
                return;
            }
            long timestamp = Long.parseLong(rowkey[1].toString());
            String userKey = rowkey[0].toString();
            Cell dataCell = null;
            Cell countCell = null;
            String type = "";
            String field = "";

            //基础信息
            for (String str1 : INFO_COLUMNS) {
                String[] fieldArray = str1.split(":");
                if (fieldArray.length > 1) {
                    field = fieldArray[0];
                    type = fieldArray[1];
                } else {
                    field = fieldArray[0];
                    type = "string";
                }
                dataCell = value.getColumnLatestCell(Bytes.toBytes("inf"),
                    Bytes.toBytes(field));
                if (dataCell != null) {
                    sb.append(
                        this.getValue(type, CellUtil.cloneValue(dataCell)));
                }
                sb.append("\t");
            }
            dataCell = value.getColumnLatestCell(Bytes.toBytes("job"),
                Bytes.toBytes("system_id"));
            type = "string";
            if (dataCell != null) {
                sb.append(this.getValue(type, CellUtil.cloneValue(dataCell)));
            }
            sb.append("\t");
            String outString = sb.toString();
            context.write(new Text(timestamp + "\t" + userKey),
                new Text(outString.substring(0, outString.lastIndexOf("\t"))));
            sb = null;
            //事件信息
            countCell = value.getColumnLatestCell(Bytes.toBytes("inf"),
                Bytes.toBytes("count"));
            if (countCell != null) {
                int count = Bytes.toInt(CellUtil.cloneValue(countCell));
                for (int i = 0; i < count; i++) {
                    int j = 0;
                    sb = new StringBuffer("");
                    for (String str1 : EVENT_COLUMNS) {
                        String[] fieldArray = str1.split(":");
                        if (fieldArray.length > 1) {
                            field = fieldArray[0];
                            type = fieldArray[1];
                        } else {
                            field = fieldArray[0];
                            type = "string";
                        }
                        dataCell = value.getColumnLatestCell(
                            Bytes.toBytes("inf"),
                            Bytes.toBytes(field + "#" + i));
                        if (dataCell != null) {
                            sb.append(this.getValue(type,
                                CellUtil.cloneValue(dataCell)));
                        }
                        if (j < EVENT_COLUMNS.length - 1) {
                            sb.append("\t");
                        }
                        j++;
                    }
                    context.write(new Text(timestamp + "\t" + userKey),
                        new Text(sb.toString()));
                    sb = null;
                }

            }
        }

        private Object getValue(String type, byte[] value) {
            switch (type) {
                case "string":
                    return value == null ? "" : Bytes.toString(value);
                case "date":
                    return value == null ? new Date(0)
                        : formatter.format(new Date(Bytes.toLong(value)));
                case "bigdecimal":
                    return value == null ? new BigDecimal(0)
                        : Bytes.toBigDecimal(value);
                case "boolean":
                    return value != null && Bytes.toBoolean(value);
                case "double":
                    return value == null ? 0 : Bytes.toDouble(value);
                case "float":
                    return value == null ? 0 : Bytes.toFloat(value);
                case "int":
                    return value == null ? 0 : Bytes.toInt(value);
                case "short":
                    return value == null ? 0 : Bytes.toShort(value);
                case "long":
                    return value == null ? 0 : Bytes.toLong(value);
                default:
                    return Bytes.toString(value);

            }
        }
    }

    public static class ExportUserBehaviorToDWReducer
            extends Reducer<Text, Text, Text, Text> {
        private MultipleOutputs<Text, Text> mos;

        @Override
        protected void setup(Context context)
                throws IOException, InterruptedException {
            this.mos = new MultipleOutputs<>(context);
        }

        @Override
        protected void cleanup(Context context)
                throws IOException, InterruptedException {
            this.mos.close();
        }

        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context)
                throws IOException, InterruptedException {
            for (Text val : values) {
                if (val.toString().split("\t").length > 6) {
                    this.mos.write("baseinfo", key, val);
                } else {
                    this.mos.write("eventinfo", key, val);
                }
            }

        }
    }
}
